<template>
  <view class="goods-detail">
    <x-navigation-bar v-if="inFullScreen" id="x-navigation-bar" :title="title" />
    <x-skeleton type="detail" v-if="!isLoad"></x-skeleton>
    <x-fixed v-if="inFullScreen && scrolled" id="x-tab-fixed" fixed ref="x-fixed" :interval="navigationHeight">
      <x-tabs :active="current" :list="tabs" underline @change="onChangeTabSwitch" />
    </x-fixed>
    <view>
      <!-- 轮播商品图 -->
      <view class="swiper-contant" :style="{'height': swiperRatio === 1 ? '750rpx' : '1000rpx'}">
        <swiper v-if="swiperImg.length > 0" class="swiper" :style="{'height': swiperRatio === 1 ? '750rpx' : '1000rpx'}" :circular="swiperImg.length > 1" :indicator-dots="indicatorDots" :autoplay="swiperImg.length > 1 ? autoplay : false" @change="swiperChange" display-multiple-items="true">
          <swiper-item v-for="(item,index) in swiperImg" :key="index">
            <view v-if="item.type === 'video'" style="width: 100%;height: 100%;">
              <video id="myVideo" @play="play" @pause="pause" @ended="ended" @fullscreenchange="fullscreenchange" style="width: 100%;height: 100%;" :src="item.url"></video>
            </view>
            <view class="swiper-item" v-if="item.type==='image'" :style="{'height': swiperRatio === 1 ? '750rpx' : '1000rpx'}">
              <x-image :src="formatOss(item.url)" :mode="swiperClip === 1 ? 'aspectFill' : 'aspectFit'"/>
            </view>
          </swiper-item>
        </swiper>
        <view class="indicatorDots">
          {{swiperImg.length > 0 ? swiperCurrent+1 : swiperCurrent}}/{{swiperImg.length}}
        </view>
      </view>
      <!--活动补贴等-->
      <p-activity
        v-if="productInfo"
        :isShowUp="productInfo.productSku.length > 1"
        :sales="productInfo.salesNum"
        :subsidyAmount="productInfo.subsidyAmount"
        :productPrice="productInfo.productSafeguard.groupMode === 1 ? productInfo.groupPrice : productInfo.purchasePrice"
        :checkCouponPrice="checkCoupon()"
        type="detail"
      />
      <!-- 轮播图下面价格部分 -->
      <view class="goods-content">
        <!-- 商品价格 -->
        <view class="price" v-if="productInfo && !productInfo.subsidyAmount">
          <x-price v-if="productInfo && couponList && couponList.length > 0 && isCouponPrice" :TipsSize="28" :Price1Size="36" :Price2Size="36" :price="productInfo.productSafeguard.groupMode === 1 ? productInfo.groupPrice : productInfo.purchasePrice" />
          <x-price v-else :TipsSize="28" :Price1Size="54" :Price2Size="54" :price="productInfo.productSafeguard.groupMode === 1 ? productInfo.groupPrice : productInfo.purchasePrice" />
          <text v-if="productInfo.productSku.length > 1" class="_up _red">起</text>
          <view class="coupon-price" v-if="productInfo && couponList && couponList.length > 0 && isCouponPrice"><text class="_coupon-after">券后¥</text><text>{{ checkCoupon() }}</text><text v-if="productInfo.productSku.length !== 1" class="_up">起</text></view>
          <text class="sales">已售{{ numberFormat(productInfo.salesNum) }}件</text>
        </view>
        <!-- 满减 -->
        <x-send-coupon v-if="couponList && couponList.length" :coupon="batchCouponInfo" @userconfirm="getBatchCouponInfo">
          <view class="discount" @click="openCouponVisible">
            <view class="_title">
                <text class="_tips" v-for="(item,index) in couponList" :key="index">
                  <text v-if="item.couponType === 1">满{{ item.transactionAmount }}</text>
                  <text v-else>立</text>
                  减{{ item.couponAmount }}元
                </text>
            </view>
            <view class="_suffix">
              <x-icon name="icon-017" color="#999999" size="8px" />
            </view>
          </view>
        </x-send-coupon>
        <!-- 品牌 -->
        <view class="brand">
          <view class="lf">
            <view class="_title">
              <!--            <view class="_tips">品牌</view>-->
              <view class="_tips" v-if="brandInfo">品牌</view>
              <view class="_name" :style="{'text-indent': brandInfo ? '90rpx' : 0 }">{{ productInfo.productTitle }}</view>
            </view>
            <view class="_vertical-line"></view>
            <view class="_introduce">{{ productInfo.productSellingPoint || ''}}</view>
          </view>
          <x-button class="rt" @click="openShareVisible" size="none" styles="background: none;">
            <view class="_share">
              <x-icon name="icon-023" size="44" color="#EB441F"></x-icon>
              <text style="color: #EB441F;font-weight: bold;">分享</text>
            </view>
          </x-button>
        </view>
        <!-- 品牌 -->
        <view class="store" v-if="brandInfo">
          <view class="_logo">
            <x-image :src="brandInfo.brandLogo"></x-image>
          </view>
          <view class="_name">{{ brandInfo.brandName }}</view>
          <view class="_vertical-line"></view>
          <view class="_introduce">{{ brandInfo.brandDesc }}</view>
        </view>
      </view>
      <!-- 服务 -->
      <p-server :serveList="pledgeList" suffix @showServiceDrawer="serviceVisible = true"/>
      <x-delivery :productSafeguard="productInfo.productSafeguard"/>
      <!-- 拼团 -->
      <view v-if="recentlyList" style="margin-top: 8px" class="collage">
        <x-carousel :list="recentlyList" :header="carouselHeader" type="group" button-text="去参团" @change="joinGroup" />
      </view>
      <!-- 用户评价 -->
      <p-apprise v-if="productInfo" :product-id="query.productId" :label="commentLabelSelected" :comment-type="productInfo.productSafeguard.productComment" class="apprise" />
      <!-- 问大家 -->
      <p-ask :product-id="query.productId" :product-name="productInfo.productTitle" :product-pic="productInfo.productMainPic" />
      <!-- 店铺 -->
      <p-store v-if="productInfo.storeId" storeEntrance storeRecommend="{value: true}" :productId="query.productId" :storeId="productInfo.storeId" :storeInfo="storeInfo" />
      <!--商品介绍/规格信息-->
      <p-details v-if="productInfo" :product-attr="productInfo.productAttrValues" :product-images="currentTabImage" class="detail-tab" />
      <!-- 看了又看 -->
      <view v-if="goodsList && goodsList.length" class="other-goods">
        <view>
          <view class="_img">
            <x-image src="/assets/images/common-recommend-look.png" mode="widthFix"></x-image>
          </view>
          <view class="recommend">
            <x-goods-list :list="goodsList" type="column" ref="goodsList" />
          </view>
        </view>
      </view>
      <!-- 底部固定栏 -->
      <!-- 固定拼团 -->
      <x-fixed ref="x-fixed-bottom" fixed direction="bottom">
        <view>
          <p-fixed-discount :price="discountPriceSum" :gift="productGiftInfo" />
          <x-collage v-if="isFooter && groupList" :detail="groupList[0]" @joinGroup="joinGroup(groupList[0])"></x-collage>
          <!-- 固定购买 -->
          <view class="bottom-fixed">
            <view class="_content">
              <view class="_lf">
                <x-button
                  v-if="isSaas"
                  styles="border: none !important;padding: 0;height: 100%;"
                  plain
                  open-type="contact"
                  :businessId="storeInfo.businessId"
                  :sendMessageTitle="shareCustomerData.cardKeywords"
                  :show-message-card="true"
                  :session-from="sessionFrom"
                  :send-message-img="shareCustomerData.cardUrl"
                >
                  <view class="_item" style="flex-direction: column">
                    <view class="icon">
                      <x-icon name="icon-001" size="40" color="#07C160" />
                    </view>
                    <text class="_text">客服</text>
                  </view>
                </x-button>
                <x-button
                  v-else-if="isOpenApp && storeInfo"
                  styles="border: none !important;padding: 0;height: 100%;"
                  plain
                  @click="handleJumpCustomer"
                >
                  <view class="_item" style="flex-direction: column">
                    <view class="icon">
                      <x-icon name="icon-001" size="40" color="#07C160" />
                    </view>
                    <text class="_text">客服</text>
                  </view>
                </x-button>
                <x-button
                  v-else-if="storeInfo && shareCustomerData && shareCustomerData.replyStatus === 1"
                  styles="border: none !important;padding: 0;height: 100%;"
                  plain
                  open-type="contact"
                  :businessId="storeInfo.businessId"
                  :sendMessageTitle="shareCustomerData.cardKeywords"
                  :show-message-card="true"
                  :session-from="sessionFrom"
                  :send-message-img="shareCustomerData.cardUrl"
                >
                  <view class="_item" style="flex-direction: column">
                    <view class="icon">
                      <x-icon name="icon-001" size="40" color="#07C160" />
                    </view>
                    <text class="_text">客服</text>
                  </view>
                </x-button>
                <x-button
                  v-else-if="storeInfo"
                  styles="border: none !important;padding: 0;height: 100%;"
                  plain
                  open-type="contact"
                  :businessId="storeInfo.businessId"
                  :session-from="sessionFrom"
                >
                  <view class="_item" style="flex-direction: column">
                    <view class="icon">
                      <x-icon name="icon-001" size="40" color="#07C160" />
                    </view>
                    <text class="_text">客服</text>
                  </view>
                </x-button>
                <x-button v-if="!isSaas" styles="border: none !important;padding: 0;height: 100%;" plain @click="onStore">
                  <view class="_item">
                    <view class="icon">
                      <x-icon name="icon-020" size="40" color="#ED6A0C" />
                    </view>
                    <text class="_text">店铺</text>
                  </view>
                </x-button>
                <x-button styles="border: none !important;padding: 0;height: 100%;" plain @click="favoritesProduct">
                  <view class="_item">
                    <view class="icon">
                      <x-icon v-if="!productInfo.favorites" name="icon-010" size="40" color="#FAAB0C" />
                      <x-icon v-else name="icon-028" size="40" color="#FAAB0C" />
                    </view>
                    <text class="_text">{{ !productInfo.favorites ? '收藏' : '已收藏' }}</text>
                  </view>
                </x-button>
              </view>
              <view v-if="productInfo && productInfo.productType === 5" class="_rt" style="height: 110rpx">
                <view class="_one" @click="openSkuVisible(2)">
                  <view class="_buy">
                    <view class="flex-column">
                      <text class="_price">¥{{ groupPurchasePrice }}</text>
                      <text class="_text">立即购买</text>
                    </view>
                  </view>
                </view>
              </view>
              <x-send-coupon v-else-if="couponList && couponList.length > 0 && !isAlreadyReceive" style="width: 100%;" :coupon="batchCouponInfo" @sendcoupon="buyCouponCallback">
                <view class="_rt" style="height: 110rpx">
                  <view class="_one" @click="openSkuVisible(1)" v-if="productInfo && productInfo.productSafeguard.groupMode === 0">
                    <view class="_buy">
                      <view class="flex-column">
                        <text class="_price">¥{{ purchasePrice }}<text v-if="productInfo.productSku.length > 1" class="_up">起</text></text>
                        <text class="_text">立即购买</text>
                      </view>
                    </view>
                  </view>
                  <view class="_two" v-if="productInfo && productInfo.productSafeguard.groupMode === 1">
                    <view class="_buy _orange"  @click="openSkuVisible(1)">
                      <view class="flex-column">
                        <text class="_price">
                          ¥{{ purchasePrice }}
                          <text v-if="productInfo.productSku.length > 1" class="_up">起</text>
                        </text>
                        <text class="_text">单独购买</text>
                      </view>
                    </view>
                    <view class="_buy"  @click="openSkuVisible(2)">
                      <view class="flex-column">
                        <text class="_price">
                          ¥{{ groupPurchasePrice }}
                          <text v-if="productInfo.productSku.length > 1" class="_up">起</text>
                        </text>
                        <text class="_text">立即开团</text>
                      </view>
                    </view>
                  </view>
                </view>
              </x-send-coupon>
              <view v-else class="_rt" style="height: 110rpx">
                <view class="_one" @click="openSkuVisible(1)" v-if="productInfo && productInfo.productSafeguard.groupMode === 0">
                  <view class="_buy">
                    <view class="flex-column">
                      <text class="_price">
                        ¥{{ purchasePrice }}
                        <text v-if="productInfo.productSku.length > 1" class="_up">起</text>
                      </text>
                      <text class="_text">立即购买</text>
                    </view>
                  </view>
                </view>
                <view class="_two" v-if="productInfo && productInfo.productSafeguard.groupMode === 1">
                  <view class="_buy _orange"  @click="openSkuVisible(1)">
                    <view class="flex-column">
                      <text class="_price">
                        ¥{{ purchasePrice }}
                        <text v-if="productInfo.productSku.length > 1" class="_up">起</text>
                      </text>
                      <text class="_text">单独购买</text>
                    </view>
                  </view>
                  <view class="_buy"  @click="openSkuVisible(2)">
                    <view class="flex-column">
                      <text class="_price">
                        ¥{{ groupPurchasePrice }}
                        <text v-if="productInfo.productSku.length > 1" class="_up">起</text>
                      </text>
                      <text class="_text">立即开团</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </x-fixed>
      <!--  弹框  -->
      <!--分享-->
      <p-drawer-share v-if="shareVisible" :visible.sync="shareVisible" :detail="productInfo" @shareImage="shareImage" />
      <!--优惠券弹框-->
      <p-drawer-coupon ref="send-coupon" v-if="couponVisible" :coupon-list="couponList" :visible.sync="couponVisible" />
      <!--服务信息弹框-->
      <p-drawer-service v-if="serviceVisible" :visible.sync="serviceVisible" :serveList="pledgeList" />
      <!--SKU弹框-->
      <p-drawer-sku
        v-if="skuVisible"
        ref="drawerSku"
        :query="query"
        :visible.sync="skuVisible"
        :detail="productInfo"
        :groupMode="productInfo.productSafeguard.groupMode"
        :orderType="orderType"
        :groupNo="groupNo"
        :groupList="groupList"
        :serveList="pledgeList"
        :allCouponList="couponList"
        :gift="productGiftInfo"
      />
      <!--分享海报-->
      <view class="p-poster" catchtouchmove="true" v-if="posterVisible">
        <view class="p-container" v-if="posterLoad">
          <view style="position: relative">
            <view class="close-icon" @click="closePoster">
              <x-icon name="icon-003" size="54" color="#CCCCCC"/>
            </view>
          </view>
          <view class="_img">
            <x-image :src="posterImage" mode="widthFix" @longpress="longpressSaveImage"></x-image>
          </view>
          <view class="save-poster" @click="saveImage">
            保存图片
          </view>
        </view>
      </view>
      <view id="qrcode-wrapper">
        <canvas type="2d" canvas-id="mycanvas" id="mycanvas" style="width: 100%;height: 100%;"></canvas>
      </view>
      <!--页面被删除-->
      <p-deleted-box v-if="isDeleted" :productId="productInfo.productId" class="p-deleted-box"></p-deleted-box>

      <!-- 悬浮客服按钮 -->
      <p-customer-service :store-info="storeInfo" :session-from="sessionFrom" :share-customer-data="shareCustomerData" :is-top="toTop" />

      <!-- 挽留弹出层 -->
      <p-pop-ups v-if="popVisible" :visible.sync="popVisible" :product="productInfo" :coupon="batchCouponInfo" @change="popUpsCouponCallback" />
    </view>
  </view>
</template>

<script>
import md5 from 'md5';
import $sr from '@/utils/x-sr';
import $config from '@/config';
import XNavigationBar from '@/components/x-navigation-bar';
import XImage from '@/components/x-image';
import XIcon from '@/components/x-icon';
import XButton from '@/components/x-button';
import XTabs from '@/components/x-tabs';
import XFixed from '@/components/x-fixed';
import XGoodsList from '@/components/x-goods-list';
import XSkeleton from '@/components/x-skeleton';
import XCollage from '@/components/x-collage';
import XPrice from '@/components/x-price';
import XCarousel from '@/components/x-carousel';
import XSendCoupon from '@/components/x-send-coupon';

import PDrawerCoupon from './components/p-drawer-coupon';
import PDrawerShare from './components/p-drawer-share';
import PDrawerService from './components/p-drawer-service';
import PDrawerSku from './components/p-drawer-sku';
import PActivity from './components/p-activity';
import PServer from './components/p-server';
import PApprise from './components/p-apprise';
import PStore from './components/p-store';
import PDeletedBox from './components/p-deleted-box';
import PPopUps from './components/p-pop-ups';

import PCustomerService from '@/pages/advertising/components/p-customer-service';
import PDetails from '@/pages/advertising/components/p-details';
import PFixedDiscount from '@/pages/advertising/components/p-fixed-discount';
import PAsk from '@/pages/advertising/components/p-ask';
import XDelivery from "@/components/x-delivery/index.vue";

export default {
  name: 'GoodsDetail',
  components: {
    XDelivery,
    PAsk,
    XIcon,
    XNavigationBar,
    XImage,
    XTabs,
    XFixed,
    XGoodsList,
    XButton,
    XPrice,
    XCollage,
    XSkeleton,
    XCarousel,
    XSendCoupon,
    PPopUps,
    PDrawerShare,
    PDrawerCoupon,
    PDrawerService,
    PDrawerSku,
    PServer,
    PApprise,
    PActivity,
    PDeletedBox,
    PStore,
    PCustomerService,
    PDetails,
    PFixedDiscount
  },
  props: {},
  data() {
    return {
      // 第三方开发平台
      isOpenApp: $config.isOpen,
      isSaas: $config.project === 'saas',
      windowInfo: wx.getWindowInfo(),
      toTop: false,
      scrolled: false,
      title: '商品详情',
      inFullScreen: true, // 是否进入全屏
      videoplay: null,
      query: null,
      isDeleted: false, // 商详页无数据，跳转404错误页面
      isLoad: false,
      navigationHeight: 0,
      navHeight: 0,
      current: 0,
      swiperCurrent: 0,
      tabs: [
        { name: '宝贝', value: '' },
        { name: '评价', value: 1 },
        { name: '详情', value: 2 },
        { name: '推荐', value: 3 }
      ],
      goodsTop: 0, // 商品主体高度
      AppriseTop: 0, // 评价模块距离顶部高度
      DetailTabTop: 0, // 评价模块距离顶部高度
      OtherGoodsTop: 0, // 评价模块距离顶部高度
      autoplay: true, // 自动播放
      indicatorDots: false, // swiper指示点
      swiperImg: [],
      swiperRatio: 1,
      swiperClip: 1,
      storeInfo: null, //  店铺
      goodsList: [],
      serveList: [], // 服务信息
      groupList: [], // 参团列表
      couponList: [], // 可领取优惠券列表
      brandInfo: null, // 品牌信息
      currentTabImage: [],
      isFooter: false,
      shareVisible: false,
      serviceVisible: false,
      couponVisible: false,
      skuVisible: false,
      orderType: 1,
      groupNo: '',
      windowHeight: null,
      posterVisible: false,
      posterImage: '',
      posterLoad: false,
      shareAppMessageImgage: '',
      // 商品评价标签
      commentLabelSelected: null,
      productInfo: null,
      shareCustomerData: {}, // 客服按钮卡片信息等
      sessionFrom: null,
      isCouponPrice: false, // 是否使用优惠券之后的价格
      // 挽留弹出窗口
      batchCouponInfo: null,
      popVisible: false,
      // 是否领过券
      isAlreadyReceive: false,
      // 领取优惠券列表请求次数
      couponRequestCount: 0,
      // 下单有礼数量
      productGiftInfo: 0
    };
  },
  computed: {
    currentTabStyle() {
      return {
        'color': '#EB441F',
        'border-color': 'none'
      };
    },
    // 参团跑马灯列表
    recentlyList() {
      if (this.groupList && this.groupList.length > 2 && this.productInfo && this.productInfo.productSafeguard.groupMode === 1) {
        return this.groupList.map((item) => {
          return {
            groupNo: item.groupNo,
            avatar: item.userHeadImg,
            name: item.userNickname,
            desc: `只差<span style="color:#DE3A2E">${item.groupBalance || 1}</span>人成团`
          };
        });
      } else {
        return null;
      }
    },
    // 跑马灯头部信息
    carouselHeader() {
      if (this.productInfo && this.recentlyList) {
        let hashCode = this.$tools.hashCode(this.productInfo.id);
        if (hashCode < 0) {
          hashCode = 0 - hashCode;
        }
        let num = hashCode % 500;
        if (num < 200) {
          num += 200 + this.recentlyList.length;
        }
        return {
          title: `${num}人已拼，可直接参与`,
          pic: '/assets/images/goods-like.png'
        };
      } else {
        return null;
      }
    },
    // 商品与店铺结合的服务承诺
    pledgeList() {
      const arr = this.serveList || [];
      // 自动同意申请退款状态：0-关闭；1-开启
      if (this.storeInfo?.autoRefundStatus && !arr.some(item => item.dictNote === '极速退款')) {
        arr.push({
          dictNote: '极速退款',
          dictValue: 0,
          remark: '未发货前，为信誉良好的消费者，提供快速处理售后的服务',
          sortNum: 1
        });
      }
      return arr;
    },
    // 商品补贴价
    subsidyAmount() {
      const { purchaseSubsidyAmount } = this.productInfo || {};
      return purchaseSubsidyAmount || 0;
    },
    // 商品价格
    purchasePrice() {
      const { purchasePrice } = this.productInfo || {};
      let price = purchasePrice - this.subsidyAmount;

      // 计算优惠券价格
      const couponList = this.couponList;
      if (couponList.length) {
        const canUse = [];
        for (let j = 0; j < couponList.length; j++) {
          if (price >= couponList[j].transactionAmount && couponList[j].usableStatus === 1) {
            canUse.push(couponList[j]);
          }
        }
        if (canUse.length > 0) {
          const couponAmount = canUse.sort((a, b) => {
            return b.couponAmount - a.couponAmount;
          })[0].couponAmount;
          price = price - couponAmount;
        }
      }

      if (price <= 0) {
        price = 0.01;
      }
      return this.$tools.formatZero(price);
    },
    // 拼团补贴价
    groupSubsidyAmount() {
      const { groupSubsidyAmount } = this.productInfo || {};
      return groupSubsidyAmount || 0;
    },
    // 拼团商品价格
    groupPurchasePrice() {
      const { groupPrice } = this.productInfo || {};
      let price = groupPrice - this.groupSubsidyAmount;

      // 计算优惠券价格
      const couponList = this.couponList;
      if (couponList.length) {
        const canUse = [];
        for (let j = 0; j < couponList.length; j++) {
          if (price >= couponList[j].transactionAmount && couponList[j].usableStatus === 1) {
            canUse.push(couponList[j]);
          }
        }
        if (canUse.length > 0) {
          const couponAmount = canUse.sort((a, b) => {
            return b.couponAmount - a.couponAmount;
          })[0].couponAmount;
          price = price - couponAmount;
        }
      }

      if (price <= 0) {
        price = 0.01;
      }
      return this.$tools.formatZero(price);
    },
    //  最大优惠金额
    discountPriceSum() {
      let price;
      let discountPriceSum;
      const { productType, productSafeguard, groupPrice, purchasePrice } = this.productInfo || {};
      if (productType === 5 || productSafeguard?.groupMode === 0) {
        price = purchasePrice - this.subsidyAmount;
        discountPriceSum = this.subsidyAmount;
      } else {
        price = groupPrice - this.groupSubsidyAmount;
        discountPriceSum = this.groupSubsidyAmount;
      }

      // 计算优惠券价格
      const couponList = this.couponList;
      if (couponList.length) {
        const canUse = [];
        for (let j = 0; j < couponList.length; j++) {
          if ((price >= couponList[j].transactionAmount || couponList[j].couponType === 2) && couponList[j].usableStatus === 1) {
            canUse.push(couponList[j]);
          }
        }
        if (canUse.length > 0) {
          const couponAmount = canUse.sort((a, b) => {
            return b.couponAmount - a.couponAmount;
          })[0].couponAmount;
          discountPriceSum += couponAmount;
        }
      }

      return discountPriceSum > 0 ? discountPriceSum : 0;
    }
  },
  // 滚动页面
  onPageScroll(e) {
    this.scrolled = e.scrollTop > 0;
    // start 滑动式，切换tab栏选择
    if (e.scrollTop > (this.goodsTop - this.navHeight - 4) && e.scrollTop < (this.AppriseTop - this.navHeight - 4)) {
      this.current = 0;
    } else if (e.scrollTop > (this.AppriseTop - this.navHeight - 4) && e.scrollTop < (this.DetailTabTop - this.navHeight - 4)) {
      this.current = 1;
    } else if (e.scrollTop > (this.DetailTabTop - this.navHeight - 4) && e.scrollTop < (this.OtherGoodsTop - this.navHeight - 4)) {
      this.current = 2;
    } else if (e.scrollTop > (this.OtherGoodsTop - this.navHeight - 4)) {
      this.current = 3;
    } else {
      this.current = 0;
    }
    // end 滑动式，切换tab栏选择
    this.toTop = e.scrollTop > this.windowInfo.windowHeight;
  },
  watch: {
    scrolled(val) {
      if (val) {
        this.initHeight();
      }
    }
  },
  onLoad(query) {
    this.query = query;
    if (query.scene) {
      const scene = this.$tools.param2Object(query.scene);
      this.query.productId = scene.id;
    } else {
      this.query.productId = query.productId || query.id;
    }

    // 存储/更新浏览记录
    this.setProductStorage();
    setTimeout(() => {
      this.createObserver();

      // 缓存cps id
      if (this.query.tx_cps_id) {
        this.$store.dispatch('app/setCpsId', {
          cpsId: this.query.tx_cps_id
        });
      }
    }, 2000);
  },
  onReady() {
    this.videoplay = uni.createVideoContext('myVideo');
  },
  onShow() {
    this.scrolled = false;
    this.getData(); //  获取商品详情
  },
  created() {
    //  获取自定义导航栏高度
    uni.createSelectorQuery().select('#x-navigation-bar').boundingClientRect((res) => {
      // 最外层盒子节点
      if (res) {
        this.navigationHeight = res.height;
      }
    }).exec();
  },
  // 分享转发
  onShareAppMessage() {
    this.$XTrack('onShareAppMessage'); // 分享动作埋点
    const path = `/pages/goods-detail/index?productId=${this.query.productId}&source=share`;
    return {
      path,
      title: this.title,
      imageUrl: this.shareAppMessageImgage
    };
  },
  methods: {
    // 格式化图片
    formatOss(url, size) {
      return this.$tools.formatOss(url, size || 600);
    },
    numberFormat(val) {
      return this.$tools.numberFormat(val);
    },
    formatZero(val) {
      return this.$tools.formatZero(val);
    },
    // 存储/更新浏览记录
    setProductStorage() {
      const data = new Date();
      data.setHours(0);
      data.setMinutes(0);
      data.setSeconds(0);
      const expire = data.getTime() + 60 * 60 * 24 * 1000;
      const productHistoryList = uni.getStorageSync('productHistory') || [];
      if (!productHistoryList.includes(this.query.productId)) {
        productHistoryList.unshift(this.query.productId);
        uni.setStorageSync('productHistory', productHistoryList);
        uni.setStorageSync('expire', expire);
      } else {
        // 有搜索记录，删除之前的旧记录，将新搜索值重新push到数组首位
        const i = productHistoryList.indexOf(this.query.productId);
        productHistoryList.splice(i, 1);
        productHistoryList.unshift(this.query.productId);
        uni.setStorageSync('productHistory', productHistoryList);
        uni.setStorageSync('expire', expire);
      }
    },
    //  获取商品详情数据
    getData() {
      const params = {
        productId: this.query.productId
      };
      this.$http({
        login: true,
        url: '/product/app/spu/detail',
        method: 'get',
        report: true,
        error: false,
        data: params
      }).then(res => {
        // productStatus		商品状态（0-下架架；1-已上架）
        if (res.data.productStatus === 0 || !res.data) {
          this.isDeleted = true;
          this.isLoad = true;
          return;
        }
        // console.log(res);
        this.productInfo = res.data ? res.data : null;

        // productSku 必须为一个数组类型的数据
        if (!this.productInfo.productSku) {
          this.productInfo.productSku = [];
        }
        this.title = res.data.productTitle ? res.data.productTitle : '商品详情';

        if (this.productInfo.skuMode !== 3) {
          // 格式化difference，确保唯一
          this.productInfo.productSku?.forEach(item => {
            const difference = [];
            // 动态生成数组分隔，避免与运营录入的字符冲突
            item.separate = md5(+new Date());
            item.skuSpec.forEach((sku) => {
              difference.push([sku.specName, sku.specValue].join('@|@|@'));
            });
            item.difference = difference.join(item.separate);
          });
        } else {
          this.productInfo?.productComboList.forEach(info => {
            // 格式化difference，确保唯一
            info.productSku?.forEach(item => {
              const difference = [];
              // 动态生成数组分隔，避免与运营录入的字符冲突
              item.separate = md5(+new Date());
              item.skuSpec.forEach((sku) => {
                difference.push([sku.specName, sku.specValue].join('@|@|@'));
              });
              item.difference = difference.join(item.separate);
            });
          });
        }

        //  视频
        const swiperImg = [];
        const indexVideoFind = res.data.productResource ? res.data.productResource.find(item => item.resourceType === String('indexVideo')) : false;
        if (indexVideoFind) {
          const indexVideo = JSON.parse(indexVideoFind.resourceContent)?.videoUrl;
          if (indexVideo) {
            swiperImg.push({ type: 'video', url: indexVideo });
          }
        }
        //  白底图
        const plainPicFind = res.data.productResource ? res.data.productResource.find(item => item.resourceType === String('plainPic')) : false;
        if (plainPicFind) {
          const plainPic = JSON.parse(plainPicFind.resourceContent)?.picUrl;
          if (plainPic) {
            swiperImg.push({ type: 'image', url: plainPic });
          }
          this.shareAppMessageImgage = plainPic || '';
        }
        //  轮播图组合
        const indexPicFind = res.data.productResource ? res.data.productResource.find(item => item.resourceType === String('indexPic')) : false;
        if (indexPicFind) {
          const indexPic = JSON.parse(indexPicFind.resourceContent)?.picList;
          const swiperRatio = JSON.parse(indexPicFind.resourceContent)?.ratio || 1;
          const swiperClip = JSON.parse(indexPicFind.resourceContent)?.clip || 1;
          for (let i = 0; i < indexPic.length; i++) {
            swiperImg.push({ type: 'image', url: indexPic[i] });
          }
          this.swiperRatio = swiperRatio;
          this.swiperClip = swiperClip;
          this.shareAppMessageImgage = indexPic[0] || '';
        }
        this.swiperImg = swiperImg;
        //  商品介图片
        const detailPicFind = res.data.productResource.filter(item => item.resourceType === String('detailPic'));
        if (detailPicFind.length > 0) {
          let detailPic = [];
          detailPicFind.map((item) => {
            const picList = JSON.parse(item.resourceContent)?.picList;
            detailPic = detailPic.concat(picList);
          });
          this.currentTabImage = detailPic;
        }
        // 服务承诺
        const serveList = [];
        const productSafeguard = res.data.productSafeguard ? res.data.productSafeguard : {};
        if (productSafeguard) {
          if (productSafeguard.deliveryTypeText) {
            const deliveryTypeText = JSON.parse(productSafeguard.deliveryTypeText);
            deliveryTypeText.map((item) => {
              serveList.push(item);
            });
          }
          if (productSafeguard.productPromiseText) {
            const productPromiseText = JSON.parse(productSafeguard.productPromiseText);
            productPromiseText.map((item) => {
              serveList.push(item);
            });
          }
          if (productSafeguard.promiseAfterText) {
            const promiseAfterText = JSON.parse(productSafeguard.promiseAfterText);
            promiseAfterText.map((item) => {
              serveList.push(item);
            });
          }
        }
        // 商品评价
        if (productSafeguard.commentLabelSelected) {
          this.commentLabelSelected = productSafeguard.commentLabelSelected || [];
        }

        this.serveList = serveList;
        this.isLoad = true;
        this.getCouponList(); // 获取商品信息后 获取可领取优惠券列表
        this.getGroupList(); //  获取商品可参团信息

        setTimeout(() => {
          // 获取商品信息后 获取品牌信息
          this.getBrandInfo();
          // 获取商品信息后 获取店铺信息
          this.getStoreInfo();
          // 获取商品信息后 获取客服
          this.getConfigData();
          // 看了又看：使用店铺商品
          this.getGoodsList();
          // 支付有礼
          this.getGiftInfo();
        }, 1000);
        if (this.query.sourceFrom) {
          this.openSkuVisible(2);
        }

        this.$XTrack('push', { // 数据埋点
          customerId: this.productInfo.storeId,
          productId: this.query.productId
        });

        // 有数上报
        const productTitle = res.data.productTitle;
        $sr.track('browse_sku_page', {
          'sku': {
            sku_id: this.query.productId,
            sku_name: productTitle
          },
          'spu': {
            spu_id: this.query.productId,
            spu_name: productTitle
          }
        });
      }).catch((err) => {
        if (/4001/.test(err.code)) {
          this.isDeleted = true;
          this.isLoad = true;
        } else {
          setTimeout(() => {
            this.getData();
          }, 1000);
        }
      });
    },
    //  获取领取优惠券列表
    getCouponList() {
      const params = {
        productId: this.query.productId,
        storeId: this.productInfo.storeId
      };
      this.$http({
        login: true,
        url: '/marketing/coupon/app/list',
        method: 'get',
        error: false,
        data: params
      }).then(res => {
        this.couponList = res.data ? res.data : [];
        this.getBatchCouponInfo();
      });
    },
    // 商品可批次领取优惠券列表
    getBatchCouponInfo() {
      this.$http({
        login: true,
        url: '/marketing/coupon/app/list/forall',
        method: 'get',
        error: false,
        data: {
          productId: this.query.productId,
          storeId: this.productInfo.storeId,
          source: 3
        }
      }).then((res) => {
        this.couponRequestCount = this.couponRequestCount + 1;
        let previousStatus = 2;
        this.batchCouponInfo = res.data;
        // 挽留
        if ((this.productInfo.subsidyAmount || this.batchCouponInfo) && this.query.source === '1027') {
          this.popVisible = this.couponRequestCount === 1;
        } else if ((this.productInfo.subsidyAmount || this.batchCouponInfo)) {
          previousStatus = 1;
        } else {
          previousStatus = 2;
        }
        // 修改中转页数据
        try {
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2] || {};
          if (prevPage.route === 'pages/transit-product/index') {
            prevPage.$vm.previousStatus = previousStatus;
          }
        } catch (e) {
          console.log('修改中转页数据 error -> ', e);
        }
      });
    },
    // 判断可否使用/并使用最优优惠券(计算优惠券最低价格！)
    checkCoupon() {
      const couponList = this.couponList;
      const canUse = [];
      const productInfo = this.productInfo;
      const subsidyAmount = productInfo.subsidyAmount ? productInfo.subsidyAmount : 0;
      const productPrice = productInfo.productSafeguard.groupMode === 1 ? this.formatZero(productInfo.groupPrice - subsidyAmount) : this.formatZero(productInfo.purchasePrice - subsidyAmount);
      for (let j = 0; j < couponList.length; j++) {
        if (productPrice >= couponList[j].transactionAmount && +couponList[j].usableStatus === 1) {
          canUse.push(couponList[j]);
        }
      }
      if (canUse.length > 0) {
        this.isCouponPrice = true;
        let maxCouponAmount = canUse[0].couponAmount;
        for (let i = 0; i < canUse.length - 1; i++) {
          maxCouponAmount = maxCouponAmount < canUse[i + 1].couponAmount ? canUse[i + 1].couponAmount : maxCouponAmount;
        }
        if (productPrice - maxCouponAmount > 0) {
          return this.formatZero(productPrice - maxCouponAmount);
        } else {
          return '0.01';
        }
      } else {
        this.isCouponPrice = false;
        // return productPrice;
        return false;
      }
    },
    //  获取品牌
    getBrandInfo() {
      if (this.productInfo.productBrand) {
        const params = {
          brandId: this.productInfo.productBrand
        };
        this.$http({
          url: '/product/brand/app/detail',
          method: 'get',
          report: false,
          data: params
        }).then(res => {
          this.brandInfo = res.data ? res.data : null;
        });
      }
    },
    //  获取商品可参团信息
    getGroupList() {
      const params = {
        productId: this.query.productId
      };
      this.$http({
        url: '/order/order/group/list',
        method: 'get',
        data: params
      }).then(res => {
        this.groupList = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    //  获取店铺信息
    getStoreInfo() {
      const params = {
        storeId: this.productInfo.storeId
      };
      this.$http({
        url: '/account/store/base/info',
        method: 'get',
        report: false,
        data: params
      }).then(res => {
        // 如果不是桃红主体的，走商家的客服
        if (res.data?.channelCompanyName !== '杭州桃红网络有限公司') {
          this.isSaas = true;
        }
        this.storeInfo = res.data;
        const { homePageId, storeLevel, storeId, autoRefundStatus } = res.data;
        this.$XTrack('ProductStoreInfo', {
          storeId,
          homePageId,
          storeLevel,
          autoRefundStatus
        });
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取客服按钮信息
    getConfigData() {
      this.$http({
        url: '/account/consulter/iu/app/detail',
        data: {
          storeId: this.productInfo.storeId
        }
      }).then(res => {
        // console.log(res);
        this.shareCustomerData = res.data || {};
        this.sessionFrom = `【商品】商品名称：${this.productInfo.productTitle}；商品ID：${this.productInfo.id}`;
      });
    },
    //  获取商品推荐信息
    getGoodsList() {
      const params = {
        storeId: this.productInfo.storeId
      };
      this.$http({
        url: '/product/app/spu/list',
        method: 'get',
        data: params
      }).then(res => {
        this.goodsList = res.data ? res.data : null;
        if (this.goodsList && this.goodsList.length > 0) {
          this.$refs.goodsList?.handleList(this.goodsList);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    //  初始化各个动态数据view高度
    async initHeight() {
      //  头部高度
      uni.createSelectorQuery().select('#x-navigation-bar').boundingClientRect((res) => { // 最外层盒子节点
        if (res) {
          const barHeight = res.height;
          this.navigationHeight = res.height;
          uni.createSelectorQuery().select('#x-tab-fixed').boundingClientRect((res) => { // 最外层盒子节点
            if (res) {
              this.navHeight = barHeight + res.height;
            }
          }).exec();
        }
      }).exec();
      //  商品主体高度
      uni.createSelectorQuery().select('.goods-content').boundingClientRect((res) => { // 最外层盒子节点
        // console.log(res, '评价高度');
        if (res) {
          this.goodsTop = res.top;
        }
      }).exec();
      //  评价高度
      uni.createSelectorQuery().select('.apprise').boundingClientRect((res) => { // 最外层盒子节点
        // console.log(res, '评价高度');
        if (res) {
          this.AppriseTop = res.top;
        }
      }).exec();
      //  商品详细信息高度
      uni.createSelectorQuery().select('.detail-tab').boundingClientRect((res) => { // 最外层盒子节点
        // console.log(res, '商品详细信息高度');
        if (res) {
          this.DetailTabTop = res.top;
        }
      }).exec();
      //  看一看商品高度
      uni.createSelectorQuery().select('.other-goods').boundingClientRect((res) => { // 最外层盒子节点
        // console.log(res, '看一看高度');
        if (res) {
          this.OtherGoodsTop = res.top;
        }
      }).exec();
    },
    //  点击切换tab栏，并跳转
    onChangeTabSwitch(e) {
      if (e === 1) {
        uni.pageScrollTo({
          duration: 0, // 过渡时间必须为0，uniapp bug，否则运行到手机会报错
          scrollTop: this.AppriseTop - this.navHeight // 滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
        });
      } else if (e === 2) {
        uni.pageScrollTo({
          duration: 0, // 过渡时间必须为0，uniapp bug，否则运行到手机会报错
          scrollTop: this.DetailTabTop - this.navHeight // 滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
        });
      } else if (e === 3) {
        uni.pageScrollTo({
          duration: 0, // 过渡时间必须为0，uniapp bug，否则运行到手机会报错
          scrollTop: this.OtherGoodsTop - this.navHeight // 滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
        });
      } else {
        //  回到顶部
        uni.pageScrollTo({
          duration: 0, // 过渡时间必须为0，uniapp bug，否则运行到手机会报错
          scrollTop: 0 // 滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
        });
      }
    },
    swiperChange(e) {
      this.swiperCurrent = e.detail.current;
      this.videoplay.pause(); // 暂停视频播放
    },
    /**
     * 创建Observer 用以参团显示隐藏
     * */
    createObserver() {
      const _observer = uni.createIntersectionObserver(this);
      _observer
        .relativeToViewport()
        .observe('.collage', (res) => {
          // console.log(res);
          this.isFooter = res.intersectionRatio === 0;
          this.$nextTick(() => {
            this.$refs['x-fixed-bottom'] && this.$refs['x-fixed-bottom'].setHeight(); // 重新渲染底部高度
          });
        });
    },
    // 用户点击参团列表去参团按钮
    joinGroup(val) {
      console.log('接收值3333', val);
      this.openSkuVisible(3, val.groupNo);
    },
    //  收藏商品
    favoritesProduct() {
      const params = {
        productId: this.query.productId
      };
      this.$http({
        url: '/product/favorites/save',
        method: 'post',
        data: params
      }).then(() => {
        this.productInfo.favorites = !this.productInfo.favorites;
      });
    },
    //  打开分享弹框
    openShareVisible() {
      this.shareVisible = true;
    },
    //  打开优惠券弹框
    openCouponVisible() {
      this.$store.dispatch('message/requestSubscribeMessage', {
        subscribeType: 2,
        subscribeNode: 102,
        subscribeContent: this.query.productId,
        storeId: this.productInfo.storeId
      });
      if (!this.batchCouponInfo) {
        this.couponVisible = true;
      }
    },
    //  打开服务信息弹框
    openServiceVisible() {
      this.serviceVisible = true;
    },
    //  打开规格选择弹框
    openSkuVisible(orderType, groupNo) {
      this.orderType = orderType;
      this.groupNo = groupNo;
      this.skuVisible = true;
    },
    // 购买按钮领券回调
    async buyCouponCallback() {
      this.getCouponList();
      this.$nextTick(() => {
        //  弹框组件
        if (this.$refs.drawerSku && this.couponList && this.couponList.length > 0) {
          this.$refs.drawerSku.initDetail();
        }
      });
    },
    // 挽留按钮领券回调
    async popUpsCouponCallback() {
      let orderType = 1;
      if (this.productInfo?.productSafeguard.groupMode === 1) {
        orderType = 2;
      }
      this.openSkuVisible(orderType);
      this.buyCouponCallback();
    },
    // 关闭分享海报
    closePoster() {
      this.posterVisible = false;
    },
    // 组件生成分享海报传值
    shareImage(query) {
      // console.log(query);
      this.posterVisible = true;
      this.posterLoad = true;
      this.posterImage = query.posterImage;
    },

    //  长按保存海报
    longpressSaveImage() {
      uni.showActionSheet({
        itemList: ['保存图片'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.saveImageToPhotosAlbum({
              filePath: this.posterImage, //    图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
              success: () => {
                uni.showToast({
                  title: '保存成功',
                  duration: 2000
                });
                this.posterVisible = false;
              },
              fail: () => {
                uni.showToast({
                  title: '保存失败',
                  duration: 2000
                });
              }
            });
          }
        },
        fail: function(res) {
          console.log(res.errMsg);
        }
      });
    },
    //  点击保存海报
    saveImage() {
      uni.saveImageToPhotosAlbum({
        filePath: this.posterImage, //    图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
        success: () => {
          uni.showToast({
            title: '保存成功',
            duration: 2000
          });
          this.posterVisible = false;
        },
        fail: () => {
          uni.showToast({
            title: '保存失败',
            duration: 2000
          });
        }
      });
    },
    onStore() {
      this.$http({
        url: '/product/store/page/app/detail',
        data: {
          storeId: this.productInfo.storeId
        }
      }).then(res => {
        if (res.data) {
          uni.navigateTo({
            url: `/pages/decorate/index?id=${res.data.id}` // 微页面（自定义配置的商城主页）
          });
        } else {
          uni.navigateTo({
            url: `/packages/store/index?storeId=${this.productInfo.storeId}` // 商城的店铺主页
          });
        }
      });
    },
    // 视频播放
    play() {
      console.log('play');
      this.autoplay = false;
    },
    // 视频暂停
    pause() {
      console.log('pause');
      this.autoplay = true;
    },
    // 视频播放结束
    ended() {
      console.log('视频播放结束');
      this.autoplay = true;
    },
    // 进入全屏
    fullscreenchange(e) {
      const fullScreen = e.detail.fullScreen; // 值true为进入全屏，false为退出全屏
      if (!fullScreen) { // 退出全屏
        this.inFullScreen = true;
      } else { // 进入全屏
        this.inFullScreen = false;
      }
    },
    // 联系客服-企业微信
    handleJumpCustomer() {
      const storeInfo = this.storeInfo || {};
      const shareCustomerData = this.shareCustomerData || {};
      const path = `/pages/goods-detail/index?productId=${this.query.productId}`;
      this.$tools.$formatCustomerServiceChat(storeInfo, shareCustomerData, path);
    },
    // 获取支付有礼配置信息
    getGiftInfo() {
      this.$http({
        error: false,
        url: '/marketing/gift/app/count',
        data: {
          productId: this.query.productId,
          storeId: this.productInfo.storeId
        }
      }).then((res) => {
        this.productGiftInfo = res.data;
      });
    }
  }
};
</script>
<style lang="scss">
@import 'styles/goods-detail.scss';
</style>
